import { SDKTools } from "../../Init/Managers/TaskSDK/SDKTools";

export class HttpClient {

    public static DEBUG = true;

    private static LOG(...args: any[]) {
        if (this.DEBUG) {
            console.log(...args);
        }
    }

    private static defaultHeaders = {
        'Content-Type': 'application/json'
    };

    public static get<T>(url: string, queryParams?: Record<string, any>, headers?: Record<string, string>): Promise<T> {
        if (queryParams) {
            let queryString = '';
            const keys = Object.keys(queryParams);
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                const value = queryParams[key];
                if (i > 0) {
                    queryString += '&';
                }
                queryString += `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
            }
            if (url.includes('?')) {
                url += '&' + queryString;
            } else {
                url += '?' + queryString;
            }
        }

        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.timeout = 10000;

            // 合并请求头
            const mergedHeaders = { ...this.defaultHeaders, ...headers };
            const headerKeys = Object.keys(mergedHeaders);
            for (let i = 0; i < headerKeys.length; i++) {
                const key = headerKeys[i];
                const value = mergedHeaders[key];
                xhr.setRequestHeader(key, value);
            }

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 400) {
                        try {
                            const response = SDKTools.isAliPay ? xhr.responseText : JSON.parse(xhr.responseText);
                            this.LOG(`GET ${url} RESPONSE: ${JSON.stringify(response)}`);
                            resolve(response);
                        } catch (e) {
                            reject(new Error(`JSON解析失败: ${e.message}`));
                        }
                    } else {
                        reject(new Error(`请求失败: ${xhr.status} ${xhr.statusText}`));
                    }
                }
            };

            xhr.ontimeout = () => reject(new Error('请求超时'));
            xhr.onerror = () => reject(new Error('网络错误'));

            xhr.send();
        });
    }

    public static post<T>(url: string, data: object, headers?: Record<string, string>): Promise<T> {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.timeout = 10000;

            // 合并请求头
            const mergedHeaders = { ...this.defaultHeaders, ...headers };
            const keys = Object.keys(mergedHeaders);
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                const value = mergedHeaders[key];
                xhr.setRequestHeader(key, value);
            }

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 400) {
                        try {
                            const response = SDKTools.isAliPay ? xhr.responseText : JSON.parse(xhr.responseText);
                            this.LOG(`POST ${url} RESPONSE: ${JSON.stringify(response)}`);
                            resolve(response);
                        } catch (e) {
                            reject(new Error(`JSON解析失败: ${e.message}`));
                        }
                    } else {
                        reject(new Error(`请求失败: ${xhr.status} ${xhr.statusText}`));
                    }
                }
            };

            xhr.ontimeout = () => reject(new Error('请求超时'));
            xhr.onerror = () => reject(new Error('网络错误'));

            xhr.send(JSON.stringify(data));
        });
    }
}